<template>
  <div>
    <van-checkbox-group v-model="result" ref="checkboxGroup">
      <!-- 商品列表 -->
      <ul class="gouwulist">
        <li class="rel" v-for="(item, index) in lists" :key="item.productId">
          <van-checkbox class="gou" :name="item.cartId">
            <div class="item">
              <img :src="item.imgUrl" alt="" class="img" />
              <div class="text">
                <p class="title">{{ item.masterName }}</p>
                <p class="flex jc-sb">
                  <span class="price"
                    >￥ {{ (item.price / 100).toFixed(2) }}</span
                  >
                </p>
              </div>
            </div>
          </van-checkbox>
          <!-- 右下角的数量 -->
          <span class="total price abs1" v-if="editing"
            >x {{ item.buyNum }}</span
          >
          <!-- 步进器 -->
          <van-stepper
            :value="item.buyNum"
            async-change
            @change="changeNum"
            :name="index"
            v-else
            class="abs1"
          />
        </li>
      </ul>
    </van-checkbox-group>

    <van-submit-bar
      :price="totalMoney"
      :button-text="editing ? '结算' : '删除'"
      @submit="onSubmit"
    >
      <van-checkbox slot="default" @click="check" :value="checked"
        >全选</van-checkbox
      >
    </van-submit-bar>
  </div>
</template>

<script>
import { Toast } from "vant";
export default {
  data() {
    return {
      // 复选框的勾选状态
      result: [],
      // 是否全选
      checked: false,
      oldvalue: 0,
    };
  },
  methods: {
    check() {
      this.checked = !this.checked;
      this.$refs.checkboxGroup.toggleAll(this.checked);
    },
    // 提交订单或删除商品
    onSubmit() {
      if (this.editing) {
        this.$emit("tijiao", this.totalMoney, this.result);
      } else {
        this.$emit("del", this.result);
      }
    },
    changeNum(value, detail) {
      if (this.oldvalue == value) {
        return 0;
      }
      this.oldvalue = value;
      Toast.loading({ forbidClick: true });
      this.$emit("changeNumber", value, detail.name);
    },
  },
  props: ["lists", "editing"],
  watch: {
    result(n, o) {
      // console.log("长度", this.lists.length);
      if (n.length === this.lists.length && this.lists.length > 0) {
        this.checked = true;
      } else {
        this.checked = false;
      }
    },
    lists(n) {
      if (n.length === 0) {
        this.checked = false;
      }
    },
  },
  computed: {
    totalMoney() {
      return this.lists
        .filter((item) => {
          return this.result.includes(item.cartId);
        })
        .reduce((sum, curr) => {
          return sum + Number(curr.price) * curr.buyNum;
        }, 0);
      // console.log(res);
    },
  },
};
</script>

<style lang="less" >
.cart-index {
  .van-checkbox__icon {
    margin: 0 5px 0 16px;
  }
  .van-submit-bar {
    bottom: 50px;
  }
  .abs1 {
    position: absolute;
    bottom: 18px;
    right: 10px;
  }
}
</style>